<template>
  <div id="event-manager">
    <v-header title="开发者应用管理" :showDownloadBtn = "false" :saveShow = "false"></v-header>
    <div class="main-cont" style="padding:0px 10px">
      <iToolbar v-on:click="handleToolClick" :buttonsObj="buttonsObj" style="margin-top:6px"></iToolbar>
      <el-container >
        <el-main>
          <el-table  :data="tableData">
            <el-table-column type="index" width="50"></el-table-column>
            <el-table-column prop="devName" label="开发者名称" width="auto">
              </el-table-column>
              <el-table-column prop="appName" label="应用名称" width="auto">
              </el-table-column>
              <el-table-column prop="appCode" label="应用编号" width="auto">
              </el-table-column>
              <el-table-column label="当前状态" width="auto">
                <template slot-scope="scope">
                  {{devStatusDict[scope.row.appStatus]}}
                </template>
              </el-table-column>
              <el-table-column prop="applyTime" label="申请时间" width="auto">
              </el-table-column>
              <el-table-column prop="onlineTime" label="上线时间" width="auto">
              </el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button type="text" size="small" v-on:click="openDevApp(scope.row)">上线</el-button>
                <el-button type="text" size="small" v-on:click="closeDevApp(scope.row)">下线</el-button>
                <el-button type="text" size="small" v-on:click="appUpdate(scope.row)">修改</el-button>
              </template>
            </el-table-column>
          </el-table>
          <el-pagination
            @current-change="handleCurrentChange"
            :current-page="currentPage"
            :page-size="pageSize"
            layout="total, prev, pager, next"
            :total="total"
            style="padding:20px 5px">
          </el-pagination>
        </el-main>
      </el-container>
    </div>
    <el-dialog :title="dialogTitle" :visible.sync="dialogFormVisible" @close="cancel('ruleForm')" width="900px">
      <el-form :model="formData" ref="ruleForm" :rules="rules" label-width="140px">
        <div class="headerinfo">填写应用信息</div>
        <el-row :gutter="24">
          <el-col :span='12'>
            <el-form-item label="开发者账户" prop="devId">
              <el-select v-model="formData.devId" placeholder="请选择" popper-class="zIndex-popper" style="width:274px">
                <el-option
                  v-for="item in listDevAcct"
                  :key="item.devId"
                  :label="item.devName"
                  :value="item.devId">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span='12'>
            <el-form-item label="应用名称" prop="appName">
              <el-input v-model="formData.appName" autocomplete="off"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24">
          <el-col :span='12'>
            <el-form-item label="应用编号" prop="appCode">
              <el-input v-model="formData.appCode" autocomplete="off"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span='12'>
            <el-form-item label="应用描述" prop="descript" v-if="addOrUpsate == 'add'">
              <el-input v-model="formData.descript" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="应用时间"  v-else>
              <el-input v-model="formData.applyTime" autocomplete="off"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24">
          <el-col :span='12' v-if="addOrUpsate == 'add'">
            <el-form-item label="网关环境"  prop="gateway" >
              <el-select v-model="formData.gateway" placeholder="请选择" popper-class="zIndex-popper" style="width:274px">
                <el-option
                  v-for="item in listGatewayEnv"
                  :key="item.gwEnvId"
                  :label="item.gwEnvName"
                  :value="item.gwEnvId">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span='12'>
            <el-form-item label="应用加签公钥"  prop="appPublicKey">
              <el-input type="textarea" v-model="formData.appPublicKey" autocomplete="off"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <div class="headerinfo">填写应用申请API信息</div>
        <div class="add-row-box">
          <el-row v-for='(oneInfo, key) in applyApInfo' :key="key">
            <el-col :span='10'>
              <el-select v-model="oneInfo.slcedOpenType" placeholder="请选择" popper-class="zIndex-popper" @change="changeOpenType($event, key)" style="width:274px">
                <el-option label="按模块开放" value="01"></el-option>
                <el-option label="按接口开放" value="02"></el-option>
              </el-select>
            </el-col>
            <el-col :span='10'>
              <el-select v-model="oneInfo.slcedApiInfo" placeholder="请选择" popper-class="zIndex-popper" style="width:274px;">
                <el-option
                  v-for="item in oneInfo.slcFun"
                  :key="item.linkId"
                  :label="item.linkName"
                  :value="item.linkId">
                </el-option>
              </el-select>
            </el-col>
            <el-col  :span='4'>
              <i class="iconfont icon-close" @click="deleteRow(key)"></i>
              <i class="iconfont icon-add" @click="addRow()"></i>
            </el-col>
          </el-row>
          <div class="add-condition pl30">
            <el-button type="primary" plain icon="el-icon-plus" size="mini" @click.native="addRow()"></el-button>
            <span>增加步骤</span>
          </div>
        </div>
        <!-- <el-row :gutter="24">
          <el-col :span='10'>
            开放类型
          </el-col>
          <el-col :span='10'>
            功能选择
          </el-col>
          <el-col :span='4'>
            操作
          </el-col>
        </el-row>
        <el-row v-for='(oneInfo, key) in applyApInfo' :key="key" style="display:inline-block" :gutter="24">
          <el-col :span='10' class="rightadd">
            <el-select v-model="oneInfo.slcedOpenType" placeholder="请选择" popper-class="zIndex-popper" @change="changeOpenType($event, key)" style="width:274px">
              <el-option label="按模块开放" value="01"></el-option>
              <el-option label="按接口开放" value="02"></el-option>
              <el-option
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </el-col>
          <el-col :span='10' class="rightadd">
            <el-select v-model="oneInfo.slcedApiInfo" placeholder="请选择" popper-class="zIndex-popper" style="width:274px;margin-left:58px">
              <el-option
                v-for="item in oneInfo.slcFun"
                :key="item.linkId"
                :label="item.linkName"
                :value="item.linkId">
              </el-option>
            </el-select>
          </el-col>
          <el-col :span='4'>
          <el-button type="text" size="small" v-on:click="deleteRow(key)" v-if="showadd" class="moerder">删除</el-button>
          </el-col>
        </el-row>
        <el-button type="text" size="small" v-on:click="" class="moerder addleft">添加</el-button> -->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="reset()">重 置</el-button>
        <el-button @click="dialogFormVisible = false">关 闭</el-button>
        <el-button type="primary" @click.native="ruleCreate('ruleForm', addOrUpsate)">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script type="text/ecmascript-6">
  import { gateWay } from '../../dict/rule-dict'
  import { VHeader } from '../../../../components'
  import ajax from '../../../../api/ajax/ajax'
  import api from '../../../../api/url'
  import iToolbar from '../../../iapadmin/comm/iToolbar/iToolbar'
  import { getDateTime } from '../../../../assets/js/index'
  export default {
    name: 'inspection-rule',
    components: {
      VHeader,
      iToolbar: iToolbar
    },
    data () {
      return {
        addOrUpsate: '',
        dialogFormVisible: false,
        dialogTitle: '',
        initFormData: {},
        showadd: false,
        showinput: false,
        editData: {},
        vdatslist: false,
        copyRowData: {},
        listDevAcct: [],
        listGatewayEnv: [],
        varlist: '',
        copyApplyApInfo: [],
        listToSave: [],
        listApiInterface: [],
        listApiModule: [],
        applyApInfo: [
          {
            slcFun: [],
            slcedOpenType: '01',
            slcedApiInfo: ''
          }
        ],
        buttonsObj: [
          {
            text: '新增',
            oprType: 'addRule'
          }
        ],
        tableData: [],
        formLabelWidth: '120px',
        formData: {
          appCode: '',
          appName: '',
          appPublicKey: '',
          appStatus: '',
          applyTime: '',
          authLinkList: [], // [{linkType: "01", linkId: "494440456583774208"}],
          descript: '',
          devId: '', // 开发者账户
          gateway: '', // 网关环境
          lastedTime: '',
          openTime: ''
        },
        // 校验规则
        rules: {
          devId: [
            { required: true, message: '请选择开发者账户', trigger: 'channge' }
          ],
          appName: [
            { required: true, message: '请输入应用名称', trigger: 'blur' }
          ],
          appCode: [
            { required: true, message: '请输入应用编号', trigger: 'blur' }
          ],
          descript: [
            { required: true, message: '请输入应用描述', trigger: 'blur' }
          ],
          gateway: [
            { required: true, message: '请选择网关环境', trigger: 'change' }
          ],
          appPublicKey: [
            { required: true, message: '请应用填写加签公钥', trigger: 'blur' }
          ]
        },
        // 分页数据
        total: 0,
        currentPage: 1,
        pageSize: 10
      }
    },
    methods: {
      // 获取列表数据
      getAllData (pageNum = 1, pageSize = 10) {
        ajax.post(api.LIST_DEV_APP + '?pageNum=' + pageNum + '&pageSize=' + pageSize, {gwtype: '00'}).then(res => {
          if (res.list.length > 0) {
            this.total = res.total
            this.pageSize = res.pageSize
            let ruleArr = res.list
            let changeArr = []
            ruleArr.forEach((item, key) => {
              item.applyTime = getDateTime(new Date(item.applyTime), 'ss')
              item.onlineTime = getDateTime(new Date(item.onlineTime), 'ss')
              changeArr.push(item)
            })
            this.tableData = changeArr
          }
        }).catch(() => {})
      },
      // 工具栏操作
      handleToolClick (opt) {
        switch (opt) {
          case 'addRule':
            this.addRule()
            break
          default:
            break
        }
      },
      // 提交保存发送请求[{linkType: "01", linkId: "494440456583774208"}]
      savePost () {
        let obj = {}
        this.applyApInfo.forEach((item, key) => {
          obj.linkType = item.slcedOpenType
          obj.linkId = item.slcedApiInfo
          this.formData.authLinkList.push(obj)
        })
        ajax.post(api.ADD_DEV_APP, this.formData, true).then(res => {
          if (res === 'success') {
            this.$message({
              type: 'success',
              message: '添加成功'
            })
            this.getAllData()
            this.dialogFormVisible = false
          }
        }).catch((err) => {
          if (err.errorMsg) {
            this.$message.error(err.errorMsg)
          }
        })
      },
      // 提交更新发送请求
      saveUpdatePost () {
        var _self = this
        this.formData.authLinkList = []
        let obj = {}
        this.applyApInfo.forEach((item, key) => {
          obj = {}
          obj.linkType = item.slcedOpenType
          obj.linkId = item.slcedApiInfo
          _self.formData.authLinkList.push(obj)
        })
        ajax.post(api.MODIFY_DEV_APP, this.formData).then(res => {
          if (res === 'success') {
            this.$message({
              type: 'success',
              message: '修改已加入审核'
            })
            this.dialogFormVisible = false
            this.formData = this.initFormData
            this.handleCurrentChange(this.varlist ? this.varlist : 1)
          }
          if (res.errorMsg) {
            this.$message.error(res.errorMsg)
          }
        }).catch(() => {})
      },
      // 提交保存新增的校验规则
      ruleCreate (formName, addOrUpsate) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            if (addOrUpsate === 'add') {
              this.savePost()
            } else if (addOrUpsate === 'update') {
              this.saveUpdatePost()
            }
          } else {
            return false
          }
        })
      },
      addRule () {
        this.copyApplyApInfo = []
        this.applyApInfo = []
        this.$refs.ruleForm && this.$refs.ruleForm.clearValidate()
        this.dialogTitle = '新增开发者应用'
        this.addOrUpsate = 'add'
        this.dialogFormVisible = true
      },
      cancel (formName) {
        this.formData = JSON.parse(JSON.stringify(this.initFormData))
        this.editData = JSON.parse(JSON.stringify(this.initFormData))
        this.applyApInfo = JSON.parse(JSON.stringify(this.copyRowData))
        this.$refs[formName].clearValidate()
        this.dialogFormVisible = false
        this.vdatslist = false
        this.applyApInfo = []
      },
      // 确认是否进行删除操作
      isDelete (ruleId) {
        this.$confirm('确定要删除当前规则吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.ruleDelete(ruleId)
        }).catch(err => {
          console.info(err)
        })
      },
      // 编辑当前行的数据
      appUpdate (rowData) {
        this.addOrUpsate = 'update'
        this.dialogTitle = '修改开发者应用'
        ajax.post(api.VIEW_DEV_APP, rowData).then(res => {
          let data = res
          let arr1 = []
          let arr2 = []
          data.applyTime = getDateTime(new Date(data.applyTime), 'ss')
          data.moduleList.forEach((item, key) => {
            let oneInfo = {}
            oneInfo.slcedOpenType = '01'
            oneInfo.slcedApiInfo = item.linkId
            oneInfo.slcFun = this.listApiModule
            arr1.push(oneInfo)
          })

          data.interfaceList.forEach((item, key) => {
            let oneInfo = {}
            oneInfo.slcedOpenType = '02'
            oneInfo.slcedApiInfo = item.linkId
            oneInfo.slcFun = this.listApiInterface
            arr2.push(oneInfo)
          })
          this.editData = JSON.parse(JSON.stringify(data))
          this.formData = JSON.parse(JSON.stringify(data))
          this.applyApInfo = [...arr1, ...arr2]
          this.copyApplyApInfo = JSON.parse(JSON.stringify(this.applyApInfo))
          this.dialogFormVisible = true
        }).catch(() => {})
      },
      // 切换分页
      handleCurrentChange (val) {
        this.getAllData(val)
        this.varlist = val
      },
      // 重置表单
      reset () {
        this.applyApInfo = this.copyApplyApInfo
        this.formData = JSON.parse(JSON.stringify(this.editData))
      },
      // 切换开放类型
      changeOpenType ($event, key) {
        if ($event === '01') {
          return this.getListApiModule(key)
        } else {
          return this.getListApiInterface(key)
        }
      },
      // 增加一行
      addRow () {
        this.vdatslist = true
        this.showinput = true
        this.showadd = true
        let copyData = JSON.parse(JSON.stringify(this.copyRowData))
        this.applyApInfo.push(copyData)
      },
      // 删除一行
      deleteRow (key) {
        if (this.applyApInfo.length === 2) {
          this.showadd = true
          } else if (this.applyApInfo.length === 1) {
            this.showadd = false
          }
        this.applyApInfo.splice(key, 1)
      },
      // 获取开发者账户列表
      getListDevAcct () {
        ajax.post(api.SELECT_LIST_DEV_APP, {}).then(res => {
          this.listDevAcct = res.list
        }).catch(() => {})
      },
      // 获取网关环境列表
      getListGatewayEnv () {
        ajax.post(api.LIST_GATEWAY_ENV, {}).then(res => {
          this.listGatewayEnv = res.list
        }).catch(() => {})
      },
      // 按接口开放查询
      getListApiInterface (key) {
        ajax.post(api.LISTAPIINTERFACE, {}).then(res => {
          this.applyApInfo[key].slcFun = this.assembleArr(res.list)
          this.applyApInfo[key].slcedApiInfo = this.applyApInfo[key].slcFun[0].linkId
        }).catch(() => {})
      },
      // 按模块开放查询
      getListApiModule (key) {
        ajax.post(api.LISTAPIMODULE, {}).then(res => {
          this.applyApInfo[key].slcFun = this.assembleArr(res.list)
          this.applyApInfo[key].slcedApiInfo = this.applyApInfo[key].slcFun[0].linkId
        }).catch(() => {})
      },
      // 重新组装功能选择下拉数组
      assembleArr (arr) {
        let obj = {}
        let changeArr = []
        arr.forEach((item, key) => {
          obj = {}
          if (item.interfaceId) {
            obj.linkName = item.interfaceName
            obj.linkId = item.interfaceId
          } else {
            obj.linkName = item.moduleName
            obj.linkId = item.moduleId
          }
          changeArr.push(obj)
        })
        return changeArr
      },
      // 上线
      openDevApp (row) {
        ajax.post(api.RE_OPEN_DEV_APP, row, true).then(res => {
          if (res === 'noAudit') {
            this.$message({
              type: 'success',
              message: '解冻成功'
            })
          }
        }).catch((err) => {
          if (err.errorMsg) {
            this.$message.error(err.errorMsg)
          }
        })
      },
      closeDevApp (row) {
        ajax.post(api.CLOSE_DEV_APP, {
          appId: row.appId,
          appStatus: row.appStatus,
          devId: row.devId
        }, true).then(res => {
          if (res === 'success') {
            this.$message({
              type: 'success',
              message: '冻结成功'
            })
          }
        }).catch((err) => {
          if (err.errorMsg) {
            this.$message.error(err.errorMsg)
          }
        })
      }
    },
    created () {
      this.getAllData()
      this.getListDevAcct()
      this.getListGatewayEnv()
      this.initFormData = JSON.parse(JSON.stringify(this.formData))
    },
    mounted () {
      ajax.post(api.LISTAPIMODULE, {}).then(res => {
        this.listApiModule = this.assembleArr(res.list)
        this.applyApInfo[0].slcFun = this.assembleArr(res.list)
        this.applyApInfo[0].slcedApiInfo = res.list[0].moduleId
        this.copyRowData = JSON.parse(JSON.stringify(this.applyApInfo[0]))
      }).catch(() => {})
      ajax.post(api.LISTAPIINTERFACE, {}).then(res => {
        this.listApiInterface = this.assembleArr(res.list)
      }).catch(() => {})
    },
    computed: {
      devStatusDict () {
        return gateWay.devStatus
      }
    }
  }
</script>

<style lang="stylus" rel="stylesheet/stylus">
  #event-manager
    height 100%
    .add-row-box
      .el-row
        margin-bottom 10px
    .el-input
      width 100% !important
    .main-cont
      width 100%
      height calc(100% - 62px)
      overflow: auto
      overflow-x hidden
    .el-dialog
      .el-col
        padding 0 12px
    .el-pagination
      padding-top 20px
    .el-dialog__body
      padding 10px 15px
      height 400px
      overflow-Y scroll
  .headerinfo
    font-size 14px
    margin-bottom 20px
  .rightadd
    margin-top 20px
  .moerder
    margin-top 25px
    float right
  .moerder.addleft
    margin-top 60px
    margin-right 65px
  .add-condition
    width 150px
    height 50px
    line-height 50px
    cursor pointer
    .el-button
      width 30px
      height 30px
      display inline-block
      padding 0
    span
      font-size 12px
      color #016dfb
      margin-left 10px
      cursor pointer
  /* .icon-close
  .icon-add
    font-size 14px !important
    margin-right 10px !important
    color #d8dce5 !important
    line-height 38px */
</style>
